/**
 * Created by wuhaiyang on 2017/4/13.
 */


import React, {Component} from 'react'

import {
    View,
    StyleSheet,
    ListView,
    Dimensions,
    RefreshControl
} from 'react-native'

import NavigationToolbar1 from '../widget/NavigationToolbar1'
import ArticleCrawlerUtil from '../util/ArticleCrawlerUtil'
import ArticleItem from './ArticleItem'
import DetailArticlePage from './DetailArticlePage'

const HOST_URL = 'http://news.wewen.io/?author=danlu_dy'
const ARTICLE_URL = "http://news.wewen.io";
export default class ArticlePage extends Component {
    constructor(props) {
        super(props)
        this.state = {
            dataSource: new ListView.DataSource({
                rowHasChanged: (r1, r2) => {
                    r1 !== r2
                }
            }),
            isLoading: false
        }
        this.apiTools = new ArticleCrawlerUtil()
    }

    componentDidMount() {
        this.onLoad()
    }

    onLoad() {
        this.updateState({
            isLoading: true
        })
        this.fetchData(HOST_URL)
    }

    updateState(dic) {
        if (!this) return
        this.setState(dic)
    }

    fetchData(url) {
        this.apiTools.fetchArticle(url)
            .then(result => {
                this.setState({
                    dataSource: this.state.dataSource.cloneWithRows(result)
                })
                this.updateState({
                    isLoading: false
                })
            }).catch(error => {
            console.log(error)
            this.updateState({
                isLoading: false
            })
        })
    }


    onItemClicked(data) {
        this.props.navigator.push({
            component: DetailArticlePage,
            params: {
                title: data.title,
                url: ARTICLE_URL + data.href
            },
            ...this.props,
        })

    }

    renderRow(data) {
        return <ArticleItem
            data={data}
            onItemClick={()=>this.onItemClicked(data)}
        />
    }

    renderContentView() {
        return <ListView
            dataSource={this.state.dataSource}
            renderRow={(data)=>this.renderRow(data)}
            refreshControl={
                <RefreshControl
                    onRefresh={()=>this.onLoad()}
                    title={'loadding'}
                    refreshing={this.state.isLoading} //
                />

            }
        />
    }

    render() {
        return (
            <View style={styles.container}>
                <NavigationToolbar1
                    title={'首页'}
                    statusBar={{
                        barStyle: 'light-content',
                        backgroundColor:'#2196f3'
                    }}
                />
                {this.renderContentView()}
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1
    },
})
